package com.magical;

import com.magical.entity.User;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 后台登录拦截器
 */
public class LoginFilter implements Filter {

    public static final String login_page="/login.html";



    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
          HttpServletRequest servletRequest = (HttpServletRequest) request;
          HttpServletResponse servletResponse = (HttpServletResponse) response;
          HttpSession session = servletRequest.getSession();

          // 获得用户请求的URI
          String path = servletRequest.getRequestURI();
          // 从session里取session信息
          User user =  (User)session.getAttribute("loginUser");

          // 登陆页面无需过滤
          if(path.indexOf("/login.html") > -1) {
                  chain.doFilter(servletRequest, servletResponse);
                  return;
          }

          // 判断如果没有取到信息,就跳转到登陆页面
          if (user == null ) {
                  // 跳转到登陆页面
                  servletResponse.sendRedirect(login_page);
              } else {
                  // 已经登陆,继续此次请求
                  chain.doFilter(request, response);
              }
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
